<?php

namespace app\admin\controller\Utils;

use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;

class FileImport
{
    /**
     * excel文件导入
     * @param $file_path_name
     * @param int $sheet_index
     * @return array
     * @throws Exception
     */
    public function ExcelImport($file_path_name, int $sheet_index = 0): array
    {
        try {
            $reader = IOFactory::createReaderForFile($file_path_name);
            $reader->setReadDataOnly(true);
            $object = $reader->load($file_path_name);
            $sheet = $object->getSheet($sheet_index);

            $maxRow = $sheet->getHighestRow(); // 取得总行数
        } catch (Exception $e) {
            throw new exception('解析文件失败');
        }

        if ($maxRow <= 1) {
            throw new exception('数据不能为空');
        }

        $data = $sheet->toArray();

        if (empty($data)) {
            throw new exception('数据不能为空');
        }

        return $data;
    }

    /**
     * 解析excel的时间
     * @param $date_str
     * @return false|string
     */
    public static function excelDateParse($date_str)
    {
        $num = floatval($date_str);

        $time = ($num - 25569) * 24 * 60 * 60;

        return date('Y-m-d H:i:s', $time) ?: '';
    }
}